package com.damuzee.core.manager.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.damuzee.common.support.message.JavaEmailSender;
import com.damuzee.core.manager.SenderManager;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 邮件发送的实现类
 * 
 * @author karka.w
 * 
 */
public class SenderManagerImpl implements SenderManager {

	private static final Logger log = LoggerFactory
			.getLogger(SenderManagerImpl.class);

	private JavaEmailSender sender;
	private FreeMarkerConfigurer freeMarkerConfigurer = null;// FreeMarker的技术类

	public void setFreeMarkerConfigurer(
			FreeMarkerConfigurer freeMarkerConfigurer) {
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}

	public void setSender(JavaEmailSender sender) {
		this.sender = sender;
	}

	// 通过模板构造邮件内容，参数username将替换模板文件中的${username}标签。
	private String getMailText(String ftlPath, Map map) throws IOException,
			TemplateException {
		// 通过指定模板名获取FreeMarker模板实例
		Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(
				ftlPath);
		// 解析模板并替换动态数据，最终username将替换模板文件中的${username}标签。
		String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
				tpl, map);
		return htmlText;
	}

	// 发送模板邮件
	public boolean sendTemplateMail(List<String> toAddresss, Map map,
			String ftlPath) throws MessagingException, IOException,
			TemplateException {
		MimeMessage msg = sender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf8");// 由于是html邮件，不是mulitpart类型
		helper.setFrom(sender.getUserName());
		// helper.setSubject("异常报告-"+report.getReportTypeName()+"-"+report.getUnusualTypeName()+"-"+report.getCreatMan());
		String htmlText = getMailText(ftlPath, map);// 使用模板生成html邮件内容
		helper.setText(htmlText, true);

		log.debug("发送邮箱的内容：{}", htmlText);

		// 循环发送邮件
		for (String toAddress : toAddresss) {
			helper.setTo(toAddress);
			sender.send(msg);
		}
		return true;
	}

	public boolean sendTemplateMail(String email, Map map, String ftlPath)
			throws MessagingException, IOException, TemplateException {
		List list = new ArrayList();
		list.add(email);
		return sendTemplateMail(list, map, ftlPath);
	}

}